using System.Collections;
using System.Collections.Generic;
using AillieoUtils;
using LFramework;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Deepseek : MonoBehaviour
{
    /// <summary>
    /// 输入框
    /// </summary>
    public TMP_InputField inputField;
    /// <summary>
    /// 发送按钮
    /// </summary>
    public Button btnSend;
    /// <summary>
    /// 聊天数据
    /// </summary>
    public List<ChatData> chatDatas = new List<ChatData>();
    /// <summary>
    /// 聊天列表
    /// </summary>
    public ScrollViewEx chatList;
    /// <summary>
    /// 聊天内容尺寸文本
    /// </summary>
    public TextMeshProUGUI sizeContent;

    private const string BaseUrl = "https://api.deepseek.com/";

    private const string ApiKey = "YOU_API_KEY";
    /// <summary>
    /// 宽度
    /// </summary>
    private float width;


    void Start()
    {
        btnSend.Subscribe(OnSendClick);

        width = chatList.GetComponent<RectTransform>().rect.width;
        sizeContent.rectTransform.sizeDelta = new Vector2(width - 130, 100);
        chatList.SetUpdateFunc(this.updateFunc);
        chatList.SetItemSizeFunc(this.itemSizeFunc);
        chatList.SetItemCountFunc(this.itemCountFunc);
    }

    void updateFunc(int index, RectTransform item)
    {
        item.gameObject.SetActive(true);
        item.GetComponent<ChatItem>().BindData(chatDatas[index]);
    }

    Vector2 itemSizeFunc(int index)
    {
        sizeContent.text = chatDatas[index].content;
        float height = sizeContent.preferredHeight;
        if (height < 100) height = 100;
        else height += 49.26f;
        return new Vector2(width, height);
    }

    int itemCountFunc()
    {
        return chatDatas.Count;
    }


    /// <summary>
    /// 点击发送
    /// </summary>
    private void OnSendClick()
    {
        if (string.IsNullOrEmpty(inputField.text))
        {
            Debug.LogError("请输入内容");
            return;
        }

        chatDatas.Add(new ChatData { isBot = false, content = inputField.text });
        StartCoroutine(SendChatRequest(inputField.text));

        chatList.UpdateData();
        chatList.ScrollTo(chatDatas.Count - 1);
        inputField.text = "";
    }

    /// <summary>
    /// 发送聊天请求
    /// </summary>  
    private IEnumerator SendChatRequest(string Message)
    {
        // 请求体
        string jsonData = "{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"user\", \"content\": \"" + Message + "\"}]}";
        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);

        using (UnityWebRequest webRequest = new UnityWebRequest(BaseUrl + "chat/completions", "POST"))
        {
            // 设置请求头和请求体
            webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = new DownloadHandlerBuffer();
            webRequest.SetRequestHeader("Content-Type", "application/json");
            webRequest.SetRequestHeader("Authorization", $"Bearer {ApiKey}");
            // 发送请求并等待响应
            yield return webRequest.SendWebRequest();

            // 检查请求是否成功
            if (webRequest.result == UnityWebRequest.Result.ConnectionError ||
                webRequest.result == UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError("Error: " + webRequest.error);
                chatDatas.Add(new ChatData { isBot = true, content = webRequest.error });
                chatList.UpdateData();
                chatList.ScrollTo(chatDatas.Count - 1);
            }
            else
            {
                // 获取服务器返回的数据
                string responseText = webRequest.downloadHandler.text;
                Debug.Log("Response: " + responseText);

                // 解析 JSON 数据
                ProcessResponse(responseText);
            }
        }
    }

    void ProcessResponse(string jsonResponse)
    {
        // 解析 JSON 数据
        OpenAIResponse response = JsonUtility.FromJson<OpenAIResponse>(jsonResponse);

        // 提取回复内容
        if (response.choices != null && response.choices.Length > 0 && response.choices[0].message != null)
        {
            string reply = response.choices[0].message.content;
            chatDatas.Add(new ChatData { isBot = true, content = reply });
            chatList.UpdateData();
            chatList.ScrollTo(chatDatas.Count - 1);
        }
        else
        {
            chatDatas.Add(new ChatData { isBot = true, content = "出错了，请稍后重试！" });
            chatList.UpdateData();
            chatList.ScrollTo(chatDatas.Count - 1);
        }
    }

    // 定义 JSON 数据结构
    [System.Serializable]
    public class OpenAIResponse
    {
        public Choice[] choices;
    }

    [System.Serializable]
    public class Choice
    {
        public Message message;
    }

    [System.Serializable]
    public class Message
    {
        public string role;
        public string content;
    }
}
